package com.cskaoyan.service;

import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.bean.wxvo.UserIndexVO;
import com.cskaoyan.bean.wxvo.WxOrder;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MarketManagementServiceImpl implements MarketManagementService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    RegionMapper regionMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    KeywordMapper keywordMapper;

    //category
    @Override
    public List<CategoryVo> getAllCategory() {

        //List<CategoryVo> categoryVo = new ArrayList<>();

        //查询LEVEL1
        CategoryExample categoryExample = new CategoryExample();

        CategoryExample.Criteria criteria1 = categoryExample.createCriteria();


        criteria1.andLevelEqualTo("L1");
        criteria1.andDeletedEqualTo(false);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        //把Category赋值给CategoryVo
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category : categories) {
            CategoryVo categoryVo1 = new CategoryVo();
            categoryVo1.setId(category.getId());
            categoryVo1.setDesc(category.getDesc());
            categoryVo1.setName(category.getName());
            categoryVo1.setKeywords(category.getKeywords());
            categoryVo1.setIconUrl(category.getIconUrl());
            categoryVo1.setLevel(category.getLevel());
            categoryVo1.setPicUrl(category.getPicUrl());

            //给children赋值

            List<CategoryVo> childList = new ArrayList<>();

            //查询pid==id且level为2的，并赋值给children
            CategoryExample categoryExample1 = new CategoryExample();
            CategoryExample.Criteria criteria = categoryExample1.createCriteria();
            criteria.andPidEqualTo(category.getId());
            //criteria.andLevelEqualTo("L2");
            List<Category> categories1 = categoryMapper.selectByExample(categoryExample1);
            //赋值给children
            for (Category category1 : categories1) {
                CategoryVo categoryVoChild = new CategoryVo();
                categoryVoChild.setId(category1.getId());
                categoryVoChild.setDesc(category1.getDesc());
                categoryVoChild.setName(category1.getName());
                categoryVoChild.setKeywords(category1.getKeywords());
                categoryVoChild.setIconUrl(category1.getIconUrl());
                categoryVoChild.setLevel(category1.getLevel());
                categoryVoChild.setPicUrl(category1.getPicUrl());

                //添加到childList
                childList.add(categoryVoChild);
            }

            categoryVo1.setChildren(childList);

            categoryVoList.add(categoryVo1);
        }

        return categoryVoList;

    }


    @Override
    public List<CategoryL1Vo> getAllCategoryL1() {

        List<CategoryL1Vo> l1Vos = categoryMapper.selectCategoryL1();

        if (l1Vos != null)

            return l1Vos;
        return null;
    }

    @Override
    public boolean deleteCategory(CategoryBo categoryBo) {

        if (categoryBo.getChildren() != null) {
            List<CategoryBo> children = categoryBo.getChildren();

            for (CategoryBo child : children) {

                Category category = new Category();

                CategoryExample categoryExample = new CategoryExample();
                CategoryExample.Criteria criteria = categoryExample.createCriteria();
                criteria.andIdEqualTo(child.getId());
                //传值
                category.setDeleted(true);
                categoryMapper.updateByExampleSelective(category, categoryExample);

            }

        }
        Category category1 = new Category();

        CategoryExample categoryExample1 = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample1.createCriteria();
        criteria.andIdEqualTo(categoryBo.getId());
        //传值
        category1.setDeleted(true);
        int i = categoryMapper.updateByExampleSelective(category1, categoryExample1);

        if (i != 0) return true;
        else return false;
    }


    @Override
    public Category insertNewCategory(Category category) {


        Date date = new Date();
        category.setAddTime(date);
        category.setUpdateTime(date);
        category.setDeleted(false);
        category.setSortOrder((byte) 0);

        int insert = categoryMapper.insert(category);

        if (insert != 0) return category;
        else return null;
    }


    @Override
    public boolean updateCategory(CategoryBo categoryBo) {


        if (categoryBo.getChildren() != null && categoryBo.getChildren().size() != 0) {

            List<CategoryBo> children = categoryBo.getChildren();
            for (CategoryBo child : children) {

                Category category = new Category();
                //一级的pid
                category.setPid(categoryBo.getPid());
                Date date = new Date();
                //更新的信息
                category.setName(child.getName());
                category.setKeywords(child.getKeywords());
                category.setDesc(child.getDesc());
                category.setIconUrl(child.getIconUrl());
                category.setPicUrl(child.getPicUrl());
                category.setUpdateTime(date);

                CategoryExample categoryExample = new CategoryExample();
                CategoryExample.Criteria criteria = categoryExample.createCriteria();
                criteria.andIdEqualTo(child.getId());

                int i = categoryMapper.updateByExampleSelective(category, categoryExample);

            }

        }
        Category categoryOne = new Category();
        categoryOne.setPid(categoryBo.getPid());
        Date date = new Date();
        //更新的信息
        categoryOne.setName(categoryBo.getName());

        categoryOne.setKeywords(categoryBo.getKeywords());

        categoryOne.setDesc(categoryBo.getDesc());

        categoryOne.setIconUrl(categoryBo.getIconUrl());

        categoryOne.setPicUrl(categoryBo.getPicUrl());

        categoryOne.setUpdateTime(date);

        categoryOne.setLevel(categoryBo.getLevel());

        categoryOne.setPid(categoryBo.getPid());

        CategoryExample categoryExample = new CategoryExample();


        //根据id查询对应列表
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andIdEqualTo(categoryBo.getId());

        int i = categoryMapper.updateByExampleSelective(categoryOne, categoryExample);
        System.out.println(i);
        if (i != 0) return true;

        return false;
    }

    //Region
    @Override
    public List<RegionVo> getAllRegion() {


        List<RegionVo> regions = regionMapper.selectAllRegion();


        return regions;

    }

    //Brand
    @Override
    public BrandVo getBrandList(BrandParamBo brandParamBo) {


        BrandVo brandVo = new BrandVo();

        List<BrandVoForList> brandVoForLists = new ArrayList<>();
        //查询所有字段
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria criteria = brandExample.createCriteria();
        if (brandParamBo.getId() != null) {
            criteria.andIdEqualTo(brandParamBo.getId());
        }
        if (brandParamBo.getName() != null) {
            criteria.andNameLike("%" + brandParamBo.getName() + "%");
        }
        criteria.andDeletedEqualTo(false);
        brandExample.setOrderByClause(brandParamBo.getSort() + " " + brandParamBo.getOrder());

        PageHelper.startPage(brandParamBo.getPage(), brandParamBo.getLimit());
        List<Brand> brands = brandMapper.selectByExample(brandExample);

        //对应赋值
        for (Brand brand : brands) {
            BrandVoForList brandVoForList = new BrandVoForList();
            brandVoForList.setId(brand.getId());
            brandVoForList.setName(brand.getName());
            brandVoForList.setDesc(brand.getDesc());
            brandVoForList.setPicUrl(brand.getPicUrl());
            brandVoForList.setSortOrder(brand.getSortOrder());
            brandVoForList.setFloorPrice(brand.getFloorPrice());
            brandVoForList.setAddTime(brand.getAddTime());
            brandVoForList.setUpdateTime(brand.getUpdateTime());
            brandVoForList.setDeleted(brand.getDeleted());
            brandVoForLists.add(brandVoForList);
        }

        PageInfo<Brand> brandPageInfo = new PageInfo<>(brands);

        brandVo.setItems(brandVoForLists);
        brandVo.setTotal(brandPageInfo.getTotal());

        return brandVo;

    }

    @Override
    public Brand addBrand(Brand brand) {

        Date date = new Date();
        brand.setAddTime(date);
        brand.setUpdateTime(date);
        brand.setDeleted(false);
        brand.setSortOrder((byte) 6);

        int i = brandMapper.insert(brand);

        if (i != 0) return brand;
        return null;
    }

    @Override
    public boolean deleteBrand(Brand brand) {

        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria criteria = brandExample.createCriteria();
        criteria.andIdEqualTo(brand.getId());
        Brand brand1 = new Brand();
        brand1.setDeleted(true);

        int i = brandMapper.updateByExampleSelective(brand1, brandExample);

        if (i != 0) return true;
        return false;

    }

    @Override
    public Brand updateBrand(Brand brand) {

        Date date = new Date();
        brand.setUpdateTime(date);
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria criteria = brandExample.createCriteria();
        criteria.andIdEqualTo(brand.getId());

        int i = brandMapper.updateByExampleSelective(brand, brandExample);

        if (i != 0) return brand;
        return null;
    }


    //WxOrder
    @Override
    public OrderListVo getOrderList(OrderListParamBo orderListParamBo) {

        OrderExample orderExample = new OrderExample();

        OrderExample.Criteria criteria = orderExample.createCriteria();
        if (orderListParamBo.getUserId() != null) {
            criteria.andUserIdEqualTo(orderListParamBo.getUserId());
        }
        if (orderListParamBo.getOrderSn() != null) {
            criteria.andOrderSnLike("%" + orderListParamBo.getOrderSn() + "%");
        }
        if (orderListParamBo.getOrder() != null) {
            orderExample.setOrderByClause(orderListParamBo.getSort() + " " + orderListParamBo.getOrder());
        }

        if (orderListParamBo.getOrderStatusArray() != null && orderListParamBo.getOrderStatusArray().length != 0) {
            Integer[] orderStatusArray = orderListParamBo.getOrderStatusArray();
            List<Short> shorts = new ArrayList<>();
            for (int i = 0; i < orderStatusArray.length; i++) {
                int s = orderStatusArray[i];
                shorts.add((short) s);
            }
            criteria.andOrderStatusIn(shorts);
        }

        PageHelper.startPage(orderListParamBo.getPage(), orderListParamBo.getLimit());
        List<Order> orders = orderMapper.selectByExample(orderExample);

        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);

        List<OrderListVoForList> ordersVos = new ArrayList<>();


        for (Order order : orders) {
            OrderListVoForList orderListVoForList = new OrderListVoForList();
            orderListVoForList.setId(order.getId());
            orderListVoForList.setUserId(order.getUserId());
            orderListVoForList.setOrderSn(order.getOrderSn());
            orderListVoForList.setOrderStatus(order.getOrderStatus());
            orderListVoForList.setConsignee(order.getConsignee());
            orderListVoForList.setMobile(order.getMobile());
            orderListVoForList.setAddress(order.getAddress());
            orderListVoForList.setMessage(order.getMessage());
            orderListVoForList.setGoodsPrice(order.getGoodsPrice());
            orderListVoForList.setFreightPrice(order.getFreightPrice());
            orderListVoForList.setCouponPrice(order.getCouponPrice());
            orderListVoForList.setIntegralPrice(order.getIntegralPrice());
            orderListVoForList.setGrouponPrice(order.getGrouponPrice());
            orderListVoForList.setOrderPrice(order.getOrderPrice());
            orderListVoForList.setActualPrice(order.getActualPrice());
            orderListVoForList.setComments(order.getComments());
            orderListVoForList.setAddTime(order.getAddTime());
            orderListVoForList.setUpdateTime(order.getUpdateTime());
            orderListVoForList.setDeleted(order.getDeleted());
            orderListVoForList.setEndTime(order.getEndTime());
            orderListVoForList.setShipSn(order.getShipSn());
            orderListVoForList.setShipChannel(order.getShipChannel());
            orderListVoForList.setShipTime(order.getShipTime());

            ordersVos.add(orderListVoForList);
        }

        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setItems(ordersVos);
        orderListVo.setTotal(orderPageInfo.getTotal());
        return orderListVo;
    }

    @Override
    public OrderDetailVo getOrderDetail(Integer id) {

//        //查询order
//        OrderDetailInnerOrderBean order = orderMapper.selectOrderByIdToVo(id);
//
//        //根据order.id查询orderGoods
//        OrderDetailInnerOrderGoodsBean orderGoodsBean = orderMapper.selectOrderGoodsByOrderId(order.getId());
//        String specification = orderGoodsBean.getSpecification();
//        ObjectMapper objectMapper = new ObjectMapper();
//        //给Specifications转换格式
//        List<String> plist = null;
//        try {
//            plist = objectMapper.readValue(specification, new TypeReference<List<String>>(){});
//        } catch (JsonProcessingException e) {
//            plist = null;
//        }
//        orderGoodsBean.setSpecifications(plist);
//        //查询user信息
//        OrderDetailInnerUserBean user = orderMapper.selectUserByUserId(order.getUserId());
//
//
//        OrderDetailVo orderDetailVo = new OrderDetailVo();
//
//        return orderDetailVo;
        //查询order
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(id);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = null;
        for (Order order1 : orders) {
            order = order1;
            break;
        }

        //根据order查询orderGoods
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
        criteria1.andOrderIdEqualTo(order.getId());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        //根据order.userid查user信息
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria2 = userExample.createCriteria();
        criteria2.andIdEqualTo(order.getUserId());
        List<User> users = userMapper.selectByExample(userExample);
        User user = null;
        for (User user1 : users) {
            user = user1;
            break;
        }


        OrderDetailVo orderDetailVo = new OrderDetailVo();

        orderDetailVo.setOrder(order);
        orderDetailVo.setOrderGoods(orderGoods);
        orderDetailVo.setUser(user);

        return orderDetailVo;
    }


    //发货
    @Override
    public void giveAShip(OrderShipBO shipBO) {
        Order order = orderMapper.selectByPrimaryKey(shipBO.getOrderId());
        order.setShipChannel(shipBO.getShipChannel());
        order.setShipSn(shipBO.getShipSn());
        Date date = new Date();
        order.setUpdateTime(date);
        order.setShipTime(date);
        order.setOrderStatus((short) 301);
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public boolean refundMoney(Integer orderId) {

        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus((short) 203);
        int update = orderMapper.updateByPrimaryKeySelective(order);
        if (update == 1) return true;
        return false;
    }

    //Issue
    @Override
    public IssueVo getAllIssue(IssueBo issueBo) {

        IssueExample issueExample = new IssueExample();
        issueExample.setOrderByClause(issueBo.getSort() + " " + issueBo.getOrder());

        IssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andDeletedEqualTo(0);

        if (issueBo.getQuestion() != null && !"".equals(issueBo.getQuestion())) {

            criteria.andQuestionLike("%" + issueBo.getQuestion() + "%");

        }
        PageHelper.startPage(issueBo.getPage(), issueBo.getLimit());
        List<Issue> issues1 = issueMapper.selectByExample(issueExample);
        PageInfo<Issue> issuePageInfo = new PageInfo<>(issues1);


        IssueVo issueVo = new IssueVo();
        issueVo.setTotal(issuePageInfo.getTotal());
        issueVo.setItems(issues1);

        return issueVo;
    }


    @Override
    public boolean updataIssues(IssuesDeleteBo issueBo) {

        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andIdEqualTo(issueBo.getId());
        Issue issue = new Issue();
        issue.setDeleted(1);
        int affectRow = issueMapper.updateByExampleSelective(issue, issueExample);

        if (affectRow != 0)
            return true;
        else return false;

    }

    @Override
    public Issue createIssues(String question, String answer) {

        if (question == null || answer == null
                || "".equals(question) || "".equals(answer)) {
            return null;
        }

        Issue issue = new Issue();

        Date date = new Date();
        issue.setQuestion(question);
        issue.setAnswer(answer);
        issue.setAddTime(date);
        issue.setDeleted(0);

        int affect = issueMapper.insert(issue);

        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andIdEqualTo(issue.getId());
        List<Issue> issues = issueMapper.selectByExample(issueExample);
        for (Issue issue1 : issues) {
            if (issue1 != null) return issue1;
        }
        return null;
    }

    @Override
    public boolean updateIssues(Issue issue) {

        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andIdEqualTo(issue.getId());

        Date date = new Date();
        issue.setUpdateTime(date);

        int affectRow = issueMapper.updateByExampleSelective(issue, issueExample);

        if (affectRow != 0)
            return true;
        else return false;

    }


    //keyWord
    @Override
    public KeyWordVO getKeyWord(KeyWordBO keyWordBO) {
        PageHelper.startPage(keyWordBO.getPage(), keyWordBO.getLimit());

        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();


        criteria.andDeletedEqualTo(false);
        // keyword
        if (keyWordBO.getKeyword() != null && !"".equals(keyWordBO.getKeyword())) {
            criteria.andKeywordLike("%" + keyWordBO.getKeyword() + "%");
        }
        // url
        if (keyWordBO.getUrl() != null && !"".equals(keyWordBO.getUrl())) {
            criteria.andUrlLike("%" + keyWordBO.getUrl() + "%");
        }

        // 分页
        keywordExample.setOrderByClause(keyWordBO.getSort() + " " + keyWordBO.getOrder());


        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        KeyWordVO keyWordVO = new KeyWordVO();
        int size = keywords.size();
        keyWordVO.setTotal(size);
        keyWordVO.setItems(keywords);

        return keyWordVO;
    }

    @Override
    public Integer delete(Keyword keyword) {
        System.out.println(keyword);
        // Keyword example
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andIdEqualTo(keyword.getId());

        // keyword record
        Keyword keywordToChange = new Keyword();
        keywordToChange.setDeleted(true);

        int affectRow = keywordMapper.updateByExampleSelective(keywordToChange, keywordExample);

        return affectRow;
    }


    @Override
    public KeyWordRespVO create(KeyWordParamBO keywordParamBO) {
        //keyword example
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        //Date
        Date date = new Date();
        //keyword
        Keyword keyword = new Keyword();
        keyword.setKeyword(keywordParamBO.getKeyword());
        keyword.setUrl(keywordParamBO.getUrl());
        keyword.setIsHot(keywordParamBO.getIsHot());
        keyword.setIsDefault(keywordParamBO.getIsDefault());
        keyword.setAddTime(date);
        keyword.setUpdateTime(date);
        keyword.setDeleted(false);

        keywordMapper.insertSelective(keyword);


        KeyWordRespVO keyWordRespVO = new KeyWordRespVO();
        Keyword getKeyword = keywordMapper.selectByPrimaryKey(keyword.getId());

        keyWordRespVO.setId(getKeyword.getId());
        keyWordRespVO.setKeyword(getKeyword.getKeyword());
        keyWordRespVO.setAddTime(getKeyword.getAddTime().toString());
        keyWordRespVO.setUpdateTime(getKeyword.getUpdateTime().toString());
        keyWordRespVO.setIsDefault(getKeyword.getIsDefault());
        keyWordRespVO.setIsHot(getKeyword.getIsHot());
        keyWordRespVO.setUrl(getKeyword.getUrl());

        return keyWordRespVO;
    }

    @Override
    public Keyword update(Keyword keyword) {
        // update
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andIdEqualTo(keyword.getId());
        //更新时间
        Date date = new Date();
        keyword.setUpdateTime(date);
        keywordMapper.updateByExampleSelective(keyword, keywordExample);


        // return data
        Keyword returnKeyword = keywordMapper.selectByPrimaryKey(keyword.getId());

        return returnKeyword;

    }

    @Override
    public UserIndexVO selectUserOrderStatus(Integer userId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        //orders.forEach(System.out::println);
        int uncomment = 0;
        int unpaid = 0;
        int unrecv = 0;
        int unship = 0;
        for (Order order : orders) {
            if (order.getOrderStatus() == 101) {
                unpaid += 1;
            } else if (order.getOrderStatus() == 301) {
                unrecv += 1;
            } else if (order.getOrderStatus() == 201) {
                unship += 1;
            } else if (order.getOrderStatus() == 401 && order.getComments() != 0) {
                uncomment += 1;
            }
        }
        //System.out.println(uncomment+"："+unpaid+"："+unrecv+"："+unship);
        UserIndexVO userIndexVO = new UserIndexVO();
        WxOrder order = new WxOrder();
        order.setUnship(unship);
        //System.out.println(unship);
        order.setUnrecv(unrecv);
        order.setUncomment(uncomment);
        order.setUnpaid(unpaid);
        userIndexVO.setOrder(order);
        return userIndexVO;

    }
}